package hah;

import com.sun.tools.javac.util.ArrayUtils;

import java.util.Arrays;

public class lookForMinum {

        //暴力解法
        public double findMedianSortedArrays2(int[] nums1, int[] nums2) {
            int[] ints = Arrays.copyOf(nums1, nums1.length + nums2.length);
            System.arraycopy(nums2, 0, ints, nums1.length, nums2.length);
            Arrays.sort(ints);
            int len=ints.length;
            if (len%2!=0){
                int a=(len-1)/2;
                return ints[a];
            }else {
                int b=len/2;
                int c=b-1;
                return (ints[b]+ints[c])/2.0;
            }

        }
        //双指针
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            if(nums1.length==0&&nums2.length!=0){
                int len=nums2.length;
                if (len%2!=0){
                    int a=(len-1)/2;
                    return nums2[a];
                }else {
                    int b=len/2;
                    int c=b-1;
                    return (nums2[b]+nums2[c])/2.0;
                }
            }
            if(nums1.length!=0&&nums2.length==0){
                int len=nums1.length;
                if (len%2!=0){
                    int a=(len-1)/2;
                    return nums1[a];
                }else {
                    int b=len/2;
                    int c=b-1;
                    return (nums1[b]+nums1[c])/2.0;
                }
            }
            int tl= nums1.length+nums2.length;
            int flag=0;
            int end=0;
            int count=0;
            if (tl%2==0){
                end=tl/2;
            }else {
                end=(tl+1)/2;
                flag=1;
            }
            int i=0;int j=0;
            while(count<end){
                if (nums1[i]<nums2[j]){
                    i++;
                    count++;
                }else if(nums1[i]>nums2[j]){
                    j++;
                    count++;
                }else {
                    i++;
                    count++;
                }
            }
            if (flag==0){
                if(i+1< nums1.length&&nums1[i+1]<nums2[j]){
                    return (nums1[i]+nums1[i+1])/2.0;
                }
                else if(j+1< nums2.length&&nums2[j+1]<nums2[i]){
                    return (nums2[j]+nums2[j+1])/2.0;
                }else {
                    return (nums1[i]+nums2[j])/2.0;
                }
            }else {
                return nums1[i]<=nums2[j]?nums1[i]:nums2[j];
            }
        }

    public static void main(String[] args) {
        int[] a1={1,2};
        int[] a2={3,4};
        new lookForMinum().findMedianSortedArrays(a1,a2);
    }
}
